<template>
  <div id="areacode" class="same-change-oldstyle">
    <div class="same-head-box">
      <div class="saem-seat-box">
        <div class="saem-seat-left">
          <span>当前位置：</span>
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item>设备中心</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/devicelist' }">设备管理</el-breadcrumb-item>
            <el-breadcrumb-item>区域码</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="saem-seat-right">
          <button class="same-search-btns same-search-export" @click="RefreshFun">刷新</button>
          <button class="same-search-btns" @click="returnBack">返回</button>
        </div>
      </div>
    </div>

    <div class="same-table-box">
      <div class="tabel_header">
        <h4 class="same-title-box">区域码下发记录</h4>
        <div class="same-left-one">
          <button class="same-search-btns" type="button" @click="dialogVisible = true">区域码下发</button>
          <button class="same-search-btns" type="button" @click="sureCompatibleIssue">兼容区域码下发</button>
        </div>
      </div>
      <div class="table_box">



        <div class="common-table-outer">
          <el-table class="common-table" v-loading="loading" header-cell-class-name="common-table-header-cell"
            :data="tableData" stripe>
            <el-table-column align="center" label="区域码名称">
              <template slot-scope="scope">
                {{ scope.row.name||'——' }}
              </template>
            </el-table-column>

            <el-table-column align="center" prop="area_code" label="区域码">
            </el-table-column>

            <el-table-column align="center" prop="type_desc" label="下发类型">
            </el-table-column>

            <el-table-column align="center" prop="status_desc" label="下发状态">
            </el-table-column>

            <el-table-column align="center" prop="add_time" label="下发时间">
            </el-table-column>

            <el-table-column align="center" label="设备回复时间">
              <template slot-scope="scope">
                {{ scope.row.reply_time||'——' }}
              </template>
            </el-table-column>
            <template slot="empty" v-if="isLoad">
              <div class="new-no-data-show">
                <img src="../../assets/images/no-data.png" alt="">
                <div>暂无相关数据</div>
              </div>
            </template>
          </el-table>

          <div class="same-page-inShow" v-if="tableData.length > 0 && isLoad">
            <!--//  分页-->
            <el-pagination background class="pull-right clearfix" @size-change="handleSizeChange"
              @current-change="handleCurrentChange" :current-page.sync="pageNo" :page-sizes="pageSizesList"
              :page-size="pageSize" layout="total, prev, pager, next, jumper, sizes" :total="totalDataNumber">
            </el-pagination>
          </div>
        </div>


      </div>
    </div>

    <!--添加-->
    <div class="addpaymentmode" v-show="compatibleIssue">
      <div class="addpaymentmodeinner">
        <div class="toptitles">
          <span>兼容区域码下发</span>
          <img src="../../../static/images/closebtn.png" @click="closemode" />
        </div>
        <div class="inputlist">
          <div class="input_item">
            <span class="lefttitle">区域码名称</span>
            <el-input type="text" name="name" v-model="name" placeholder="请输入区域码名称" style="width:337px" />
            <i class="icon">*</i>
          </div>
          <div class="input_item">
            <span class="lefttitle">区域码</span>
            <!-- <el-input type="text" name="name" v-model="area_code"  placeholder="默认系统自动生成" style="width:337px" /> -->
            <div>
              <div class="listonlybox">
                <div class="onlyOne" v-for="(item,index) in inputList" :key="index">
                  <input type="text" autocomplete="off" maxlength="1" v-model="item.val"
                    @keyup="nextFocus($event,index)" @keydown="changeValue(index)" @input="changeInput(item.val,index)"
                    class="border-input" style="width:40px;margin-right:5px" />
                </div>
              </div>
              <div class="icon onlyHint">必须是6位数，数字0-9和字母A-F的组合,不区分大小写</br>不填系统将自动生成</div>
            </div>

            <i class="icon"></i>
          </div>
          <div class="input_item">
            <span class="lefttitle">A秘钥</span>
            <el-select v-model="keyAIndex" placeholder="请选择A秘钥" @change="handleKeyA">
              <el-option v-for="(item,index) in arrlistA" :key="item.name" :value="index" :label="item.name">
              </el-option>
            </el-select>
            <i class="icon">*</i>
          </div>
          <div class="input_item">
            <span class="lefttitle">B秘钥</span>
            <el-select v-model="keyBIndex" placeholder="请选择B秘钥" @change="handleKeyB">
              <el-option v-for="(item,index) in arrlistB" :key="item.name" :value="index" :label="item.name">
              </el-option>
            </el-select>
            <i class="icon"></i>
          </div>

          <div class="bottomBtn">
            <button @click="addAreaCode">确认下发</button>
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose" center>
      <div class="el-dialog-box">
        <h3>请选择需要下发的区域码 <el-button @click="jumpAreaCode" size="mini" slot="append" icon="el-icon-circle-plus">添加区域码
          </el-button>
        </h3>
        <el-radio-group v-model="radios_areaCode">
          <el-radio v-for="(item, index) in areaCodeList" :key="index" :label="item.id">
            <div class="item-rad">
              {{item.name}}
              <div class="code_hint">(<span>{{item.area_code}} </span>)</div>
            </div>
          </el-radio>
        </el-radio-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureIssue">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  var is_commit = true;
  export default {
    name: "areacode",
    data: function () {
      return {
        equipment_id: '',//设备id
        compatibleIssue: false,//兼容下发弹窗
        pageNo: 1,
        pageSize: 15,
        pageSizesList: [15, 30, 40, 50],
        tableData: [], // 返回的结果集合
        totalDataNumber: 0, // 数据的总数,-----
        isLoad: false,
        loading: true, //加载动画

        name: "", //名称
        area_code: '',
        inputList: [{ val: "0" }, { val: "0" }, { val: "" }, { val: "" }, { val: "" }, { val: "" }],
        arrlistA: [],
        keyA: '',
        keyAIndex: '',
        arrlistB: [],
        keyB: '-1',
        keyBIndex: "",

        areaCodeList: '',//区域码列表
        dialogVisible: false,//是否打开下发提示框
        radios_areaCode: '',//当前选中园区区域码IDIDIDID
      }
    },
    // 初始化执行
    created: function () {
      this.equipment_id = this.$route.query.equipment_id; // 接收设备ID
      this.getEquipmentAreaCode();//获取下发区域码记录
      this.getCardMotherKeyConfig();//获取秘钥信息
      this.getAreaCode();
    },
    inject: [
      'reload'
    ],
    //进入之前
    beforeRouteEnter(to, from, next) {
      to.meta.keepAlive = true;
      next(vm => {
        console.log('取到的值>>>>>', from.query.areacodes_id, to.meta.areacodes_id)
        //新增的区域码id  to.meta.areacodes_id
        var areacodes_id = to.meta.areacodes_id ? to.meta.areacodes_id : '';
        if (from.query.is_areacode == 1 && areacodes_id) {
          vm.getAreaCode();//重新获取区域码列表
          vm.radios_areaCode = areacodes_id;
          vm.dialogVisible = true;
        }

      })
    },
    //离开之前
    beforeRouteLeave(to, from, next) {
      let updates = ["/areaCodeAdd"];
      if (updates.includes(to.path)) {
        from.meta.keepAlive = true;
      } else {
        from.meta.keepAlive = false;
      }
      //console.log('from',this.areacodes_id,from.path,from.meta)
      //console.log('to',this.areacodes_id,to.path,to.meta)
      next();
    },
    methods: {

      handleKeyA(e) {
        this.keyAIndex = e;
        this.keyA = this.arrlistA[e].value
      },
      handleKeyB(e) {
        this.keyBIndex = e;
        this.keyB = this.arrlistB[e].value
      },

      //快捷添加区域码
      jumpAreaCode() {
        this.dialogVisible = false;
        this.$router.push({ path: '/areaCodeAdd', query: { is_areacode: 1 } });
      },
      handleClose(done) {
        done();
      },
      //获取区域码
      getAreaCode() {
        this.$post({
          url: "Partner/CardMother/cardMotherList",
          success: res => {
            if (res.code == 1000) {
              const data = res.data.data;
              this.radios_areaCode = data[0].id;//默认选中第一个
              this.areaCodeList = data;
              // console.log(data);
            } else {
              // this.$message.error(res.message);
            }
          }, error: e => {
            this.$message.error("获取区域码失败");
          }
        })
      },
      RefreshFun() {
        // 调用reload方法，刷新整个页面
        this.reload()
      },
      //返回
      returnBack() {
        this.$router.back(-1);
      },
      changeInput(val, idx) {
        // this.$message.closeAll();
        // let gettype = val.toString().replace(/[^A-Fa-f0-9]/g, '');
        // console.log('>>>>',val,gettype,!gettype);
        // if(gettype==''&&val!=""){
        //      this.$message.error('只能是0-9A-F的字母');
        //      this.inputList[idx].val = "";
        //      return false;
        // }
      },
      /*对焦到下一个input框去*/
      nextFocus(el, index) {
        this.$message.closeAll();
        let gettype = el.key.toString().replace(/[^A-Fa-f0-9]/g, '');
        // console.log('聚焦',el.key,index,gettype);
        if (gettype == '' && el.key != "") {
          this.$message.error('区域码必须是6位且为0-9的数字和a-f的字母组合');
          this.inputList[index].val = "";
          return false;
        }
        var dom = document.getElementsByClassName("border-input"),
          currInput = dom[index],
          nextInput = dom[index + 1],
          lastInput = dom[index - 1];
        /*这里的keyCode 根据不同的平台或许不同,安卓就是不是8*/
        if (el.keyCode != 8) {
          if (index < (this.inputList.length - 1)) {
            nextInput.focus();
          } else {
            currInput.blur();
          }
        } else {
          if (index != 0) {
            lastInput.focus();
          }
        }
        var getList = this.inputList;
        var contCat = '';
        getList.forEach((item, index) => {
          if (item.val) {
            contCat += item.val;
          }
        })
        this.area_code = contCat;
        // console.log('contCat',contCat)
      },
      /*当键盘按下的时候清空原有的数*/
      changeValue(index) {
        // this.inputList[index].val = "";
      },
      // 下发
      sureIssue() {
        if (this.radios_areaCode == '') {
          this.$message.error('区域码有误,请重新选中区域码下发!');
          return fasle;
        }
        this.$post({
          url: 'Common/Equipment/setAreaCode',
          data: { equipment_control_id: this.equipment_id, type: 1, area_code_id: this.radios_areaCode },
          success: data => {
            if (data.code == 1000) {
              this.$message.success('区域码下发成功');
              //成功后更新列表，且在当前页和当前每页条数
              this.getEquipmentAreaCode();
              this.dialogVisible = false;
            } else {
              this.$message.error(data.message);
            }
          }
        });
      },
      // 显示兼容下发弹窗
      sureCompatibleIssue() {
        this.compatibleIssue = true;
      },
      // 关闭兼容下发弹窗
      closemode() {
        this.compatibleIssue = false;
      },

      // 每页
      handleSizeChange(val) {
        var that = this;
        that.pageNo = 1;
        that.pageSize = val; // 当前每页显示条数
        that.getEquipmentAreaCode(); // 获取设备列表数据
      },
      // 分页
      handleCurrentChange(val) {
        var that = this;
        that.pageNo = val;
        that.getEquipmentAreaCode(); // 获取设备列表数据
      },
      // 获取下发区域码记录
      getEquipmentAreaCode: function () {
        this.loading = true; //打开loading动画
        this.isLoad = false;
        var that = this;
        // ajax请求
        that.$post({
          url: 'Common/Equipment/getEquipmentAreaCode',
          data: {
            page: that.pageNo,
            pageSize: that.pageSize,
            equipment_control_id: that.equipment_id,
          },
          success: data => {
            this.loading = false; //关闭动画
            this.isLoad = true;
            if (data.code == 1000) {
              that.tableData = data.data.list;
              that.totalDataNumber = Number(data.data.count); // 总的数据
            } else {
              that.tableData = []; // 清空数据
            }
          }
        });
      },
      //获取A秘钥和B秘钥
      getCardMotherKeyConfig() {
        var that = this;
        // Ajax请求 type:1通用 2兼容
        that.$post({
          url: "Common/Common/getCardMotherKeyConfig",
          data: {
            type: 2
          },
          success: data => {
            // console.log('得到的数据',data);
            if (data.code == 1000) {
              that.arrlistA = data.data.key;
              var temp = data.data.key_b;
              // temp.unshift({name: "--请选择--", value: "-1"});
              that.arrlistB = temp;
              // 赋默认值
              if (data.data.key) {
                that.keyA = data.data.key[0].value;
                that.keyAIndex = 0;
              }
              if (data.data.key_b) {
                that.keyB = data.data.key_b[0].value;
                that.keyBIndex = 0;
              }
            } else {
              that.$message.error(data.message);
            }
          }
        });
      },
      //兼容下发区域码
      addAreaCode() {
        var that = this;
        var name = that.name;
        var keyA = that.keyA;
        var keyB = that.keyB;
        var area_code = that.area_code == '00' ? '' : that.area_code;
        that.$message.closeAll();
        if (name == '') {
          that.$message.error('区域码名称不能为空'); return false;
        }
        if (keyA == '') {
          that.$message.error('A秘钥不能为空'); return false;
        }
        if (area_code.length <= 5 && area_code.length >= 3) {
          that.$message.error('区域码必须是6位'); return false;
        }
        if (!is_commit) {
          return false;
        }
        is_commit = false;
        // Ajax请求
        that.$post({
          url: "Common/Equipment/setAreaCode",
          data: {
            equipment_control_id: this.equipment_id,
            type: 2,
            name: name,
            area_code: area_code,
            key: keyA,
            key_b: keyB == '-1' ? '' : keyB,
          },
          success: data => {
            if (data.code == 1000) {
              that.$message.success('下发成功');
              that.closemode();
              that.getEquipmentAreaCode();
              that.name = '';
              that.inputList = [{ val: "0" }, { val: "0" }, { val: "" }, { val: "" }, { val: "" }, { val: "" }];
              that.area_code = '';
            } else {
              that.$message.error(data.message);
            }
            is_commit = true;
          }
        });
      },
    },
    mounted() {

    },
    watch: {

    }
  }
</script>
<style scoped>
  #areacode .el-dialog-box .el-radio {
    width: 90%;
    margin-bottom: 20px;
    font-size: 16px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  #areacode .el-dialog-box .item-rad {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    /* flex-direction: column; */
  }

  #areacode .el-dialog-box h3 {
    padding-bottom: 20px;
    position: relative;
  }

  #areacode .el-dialog-box h3 .el-button {
    position: absolute;
    top: 0px;
    right: 0px;
  }

  #areacode .el-dialog-box .code_hint {
    font-size: 12px;
    padding-left: 8px;
  }

  #areacode .el-dialog-box .code_hint span {
    color: red;
    font-weight: bold;
  }

  .areacodewrap {
    padding: 0 40px;
  }

  #areacode .same-head-box {
    border: none;
  }

  #areacode .tabel_header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  #areacode .addpaymentmode {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.3);
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
  }

  #areacode .addpaymentmodeinner {
    width: 853px;
    height: 500px;
    border: 1px solid #060001;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    background-color: #fff;
    /* overflow-y: scroll; */
  }

  #areacode .addpaymentmodeinner .toptitles {
    height: 10%;
    background-color: #2c5586;
    padding: 0 20px;
    color: #fff;
    font-size: 20px;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  #areacode .addpaymentmodeinner .toptitles img {
    cursor: pointer;
  }

  #areacode .addpaymentmodeinner .inputlarge {
    height: 40px;
    border: 1px solid #dededf;
    border-radius: 4px;
    text-indent: 1em;
  }

  #areacode .addpaymentmodeinner .inputlist {
    width: 60%;
    margin: 0 auto;
    padding-top: 20px;
  }

  #areacode .addpaymentmodeinner .severshow {
    position: absolute;
    top: 0px;
    width: 96%;
    height: 96%;
    background: #fff;
    -webkit-transition: all .7s;
    transition: all 0.7s;
    padding: 2%;
  }

  #areacode .addpaymentmodeinner .input_item {
    display: flex;
    align-items: center;
    margin: 20px 0;
  }

  #areacode .addpaymentmodeinner .input_item .lefttitle {
    width: 20%;
    font-weight: bold;
  }

  #areacode .addpaymentmodeinner .input_item input {
    width: 80%;
  }

  #areacode .addpaymentmodeinner .input_item .el-input input {
    height: 42px;
    width: 120px;
  }

  #areacode .addpaymentmodeinner .input_item .icon {
    font-style: normal;
    margin-left: 5px;
    color: #FF6565;
  }

  #areacode .addpaymentmodeinner .bottomBtn button {
    color: #fff;
    background-color: #2c5586;
    width: 150px;
    height: 35px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-top: 50px;
  }

  #areacode .listonlybox {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  #areacode .onlyOne input {
    width: 40px;
    height: 38px;
    padding: 0px;
    text-align: center;
  }

  #areacode .onlyHint {
    font-size: 12px;
    margin-top: 3px;
  }
</style>